package com.smart.translator.data;

import android.content.Context;
import android.util.Log;
import com.smart.translator.util.ConfigManager;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

/**
 * 用户API服务类
 */
public class UserApiService {
    private static final String TAG = "UserApiService";
    
    // 注册接口
    private static final String REGISTER_ENDPOINT = "/v1/UserRegister";
    // 登录接口
    private static final String LOGIN_ENDPOINT = "/v1/UserLogin";

    /**
     * 获取服务器地址
     */
    private static String getServerUrl(Context context) {
        try {
            android.content.SharedPreferences prefs = context.getSharedPreferences("app_config", Context.MODE_PRIVATE);
            return prefs.getString("server_url", "qixin.yeshan.fun");
        } catch (Exception e) {
            Log.e(TAG, "获取服务器地址失败", e);
            return "qixin.yeshan.fun";
        }
    }
    
    /**
     * 构建完整的API URL
     */
    private static String buildApiUrl(Context context, String path) {
        String serverUrl = getServerUrl(context);
        return "http://" + serverUrl + path;
    }

    /**
     * 用户注册
     */
    public static CompletableFuture<ApiResponse<User>> register(Context context, String username, String phone, String email, String password) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                String registerUrl = buildApiUrl(context, REGISTER_ENDPOINT);
                
                // 构建请求JSON
                JSONObject requestJson = new JSONObject();
                requestJson.put("username", username);
                requestJson.put("phone", phone);
                requestJson.put("email", email);
                requestJson.put("password", password);

                // 发送请求
                HttpURLConnection connection = (HttpURLConnection) new URL(registerUrl).openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);

                // 发送请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestJson.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                // 读取响应
                int responseCode = connection.getResponseCode();
                StringBuilder response = new StringBuilder();
                
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                }

                Log.d(TAG, "注册响应: " + response.toString());

                if (responseCode == 200) {
                    // 注册成功
                    JSONObject jsonResponse = new JSONObject(response.toString());
                    User user = new User();
                    user.setId(jsonResponse.optInt("id", 0));
                    user.setMessage(jsonResponse.optString("message", "注册成功"));
                    return ApiResponse.success(user);
                } else {
                    // 注册失败
                    JSONObject errorResponse = new JSONObject(response.toString());
                    String errorMessage = errorResponse.optString("detail", "注册失败");
                    return ApiResponse.error(errorMessage);
                }

            } catch (Exception e) {
                Log.e(TAG, "注册请求失败", e);
                return ApiResponse.error("网络请求失败: " + e.getMessage());
            }
        });
    }

    /**
     * 用户登录
     */
    public static CompletableFuture<ApiResponse<User>> login(Context context, String username, String password) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                String loginUrl = buildApiUrl(context, LOGIN_ENDPOINT);
                
                // 构建请求JSON
                JSONObject requestJson = new JSONObject();
                requestJson.put("username", username);
                requestJson.put("password", password);

                // 发送请求
                HttpURLConnection connection = (HttpURLConnection) new URL(loginUrl).openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);

                // 发送请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestJson.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                // 读取响应
                int responseCode = connection.getResponseCode();
                StringBuilder response = new StringBuilder();
                
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                }

                Log.d(TAG, "登录响应: " + response.toString());

                if (responseCode == 200) {
                    // 登录成功
                    JSONObject jsonResponse = new JSONObject(response.toString());
                    User user = new User();
                    // 根据服务器响应格式，id字段就是用户ID
                    int userId = jsonResponse.optInt("id", 0);
                    user.setId(userId);
                    user.setUsername(jsonResponse.optString("username", ""));
                    user.setPhone(jsonResponse.optString("phone", ""));
                    user.setEmail(jsonResponse.optString("email", ""));
                    user.setMessage(jsonResponse.optString("message", "登录成功"));
                    
                    Log.d(TAG, "登录成功，用户ID: " + userId);
                    return ApiResponse.success(user);
                } else {
                    // 登录失败
                    JSONObject errorResponse = new JSONObject(response.toString());
                    String errorMessage = errorResponse.optString("detail", "登录失败");
                    return ApiResponse.error(errorMessage);
                }

            } catch (Exception e) {
                Log.e(TAG, "登录请求失败", e);
                return ApiResponse.error("网络请求失败: " + e.getMessage());
            }
        });
    }
} 